package com.frxuexi.park.view

import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.entity.KeyBeanItem
import com.frxuexi.lib_base.entity.ParkBeanItem
import com.frxuexi.lib_base.http.Const
import com.frxuexi.lib_base.http.RequestType
import com.frxuexi.lib_base.mvi.BaseActivity
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.park.intent.ParkIntent
import com.frxuexi.park.viewmodel.ParkViewModel
import com.frxuexi.park.R
import com.frxuexi.park.databinding.ActivityParkAddBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = "/park/ParkAddActivity")
@AndroidEntryPoint
class ParkAddActivity : BaseActivity<ActivityParkAddBinding, ParkIntent, ParkViewModel>() {
    override val binding: ActivityParkAddBinding by lazy { ActivityParkAddBinding.inflate(layoutInflater) }
    override val vm: ParkViewModel by viewModels<ParkViewModel>()
    var areaId=-1
    var area=""
    var typeName=""
    var status="空闲"
    lateinit var areas:List<KeyBeanItem>
    lateinit var mytypes:List<String>
    @JvmField
    @Autowired
    var id:Int?=-1

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        when(it.type){
                            RequestType.DEFAULT->{
                                if(id!=-1) {
                                    vm.sendIntent(ParkIntent.getParkById(id!!))
                                }
                                val items = it.data as Collection<KeyBeanItem>
                                areas=items.filter { it.key=="parkArea" }
                                val areaAdapter = ArrayAdapter(
                                    this@ParkAddActivity,
                                    android.R.layout.simple_spinner_item,
                                    areas.map { it.value }
                                )
                                areaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
                                binding.parkaddArea.adapter=areaAdapter
                                binding.parkaddArea.onItemSelectedListener=object :OnItemSelectedListener{
                                    override fun onItemSelected(
                                        parent: AdapterView<*>?,
                                        view: View?,
                                        position: Int,
                                        id: Long
                                    ) {
                                        val item = areas.get(position)
                                        areaId=item.id
                                        area=item.value
                                    }

                                    override fun onNothingSelected(parent: AdapterView<*>?) {
                                    }
                                }


                                val types=items.filter { it.key=="park" }
                                mytypes=types.map { it.value }
                                val typeAdapter = ArrayAdapter(
                                    this@ParkAddActivity,
                                    android.R.layout.simple_spinner_item,
                                    mytypes
                                )
                                typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
                                binding.parkaddType.adapter=typeAdapter
                                binding.parkaddType.onItemSelectedListener=object :OnItemSelectedListener{
                                    override fun onItemSelected(
                                        parent: AdapterView<*>?,
                                        view: View?,
                                        position: Int,
                                        id: Long
                                    ) {
                                       typeName=types.get(position).value
                                    }

                                    override fun onNothingSelected(parent: AdapterView<*>?) {
                                    }
                                }
                            }
                            RequestType.ADD->{
                                ToastUtils.showLong("添加成功")
                                finish()
                            }
                            RequestType.UPDATE->{
                                ToastUtils.showLong("修改成功")
                                finish()
                            }
                            RequestType.SELECT_ITEM->{
                                val item = it.data as ParkBeanItem
                                binding.parkaddNo.setText(item.spaceNumber)
                                binding.parkaddRemark.setText(item.remarks)
                                binding.parkaddStatus.apply {
                                    binding.parkGroup.visibility=View.GONE
                                    when(item.spaceStatus){
                                        "空闲"-> check(R.id.parkadd_kx)
                                        "已占用"->{
                                            check(R.id.parkadd_zy)
                                            binding.parkGroup.visibility=View.VISIBLE
                                            binding.parkaddUser.setText(item.userName)
                                            binding.parkaddCar.setText(item.licensePlate)
                                        }
                                        else->check(R.id.parkadd_wh)
                                    }
                                }
                                binding.parkaddArea.setSelection(areas.map { it.value }.indexOf(item.areaName))
                                binding.parkaddType.setSelection(mytypes.indexOf(item.spaceType))
                            }

                            else -> {}
                        }
                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {
        ARouter.getInstance().inject(this)
        vm.sendIntent(ParkIntent.getKeys)



        binding.parkaddRemark.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val length = s?.length
                binding.parkaddNum.apply {
                    setText("${length}/10")
                    if(length==10){
                        setTextColor(this@ParkAddActivity.getColor(com.frxuexi.lib_base.R.color.redfont))
                    }else{
                        setTextColor(this@ParkAddActivity.getColor(com.frxuexi.lib_base.R.color.darkgray))
                    }
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })

        binding.parkaddStatus.setOnCheckedChangeListener { group, checkedId ->
            binding.parkGroup.visibility=View.GONE
            when(checkedId){
                R.id.parkadd_kx->status="空闲"
                R.id.parkadd_zy->{
                    status="已占用"
                    binding.parkGroup.visibility=View.VISIBLE
                }
                R.id.parkadd_wh->status="维修中"
            }
        }

        binding.parkaddSave.setOnClickListener {
            val no = binding.parkaddNo.text.toString()
            val num = binding.parkaddCar.text.toString()
            val remark = binding.parkaddRemark.text.toString()
            val user = binding.parkaddUser.text.toString()

            val item = ParkBeanItem(
                areaId,
                area,
                null,
                num,
                remark,
                no,
                status,
                typeName,
                SPUtils.getInstance().getInt(Const.UID),
                user,0
            )
            if(id!=-1){//修改
                item.id=id
                vm.sendIntent(ParkIntent.updatePark(id!!,item))
            }else {
                vm.sendIntent(ParkIntent.addPark(item))
            }
        }
    }

}